class CookieStorage {
  /**
   * @description: 设置cookie
   * @param {string} key
   * @param {string} value
   * @param {number} days
   * @param {object} options
   * @return {void}
   */
  setItem(key, value, days, options = {}) {
    if (value !== undefined) {
      let expires;
      if (typeof days === 'number') {
        expires = new Date();
        expires.setTime(+expires + days * 864e+5);
      }
      return (document.cookie = [
        encodeURIComponent(key), '=', encodeURIComponent(value),
        expires ? '; expires=' + expires.toUTCString() : '',
        options.path ? '; path=' + options.path : '',
        options.domain ? '; domain=' + options.domain : '',
        options.secure ? '; secure' : '',
      ].join(''));
    }
  }
  /**
   * @description: 获取cookie
   * @param {string} key
   * @return {string}
   */
  getItem(key) {
    let result = null;
    if (document.cookie) {
      document.cookie.split('; ').some(item => {
        const parts = item.split('=');
        const keyStr = parts.shift();
        if (keyStr && keyStr === encodeURIComponent(key)) {
          result = decodeURIComponent(parts.join('='));
          return true;
        }
      });
    }
    return result;
  }
  /**
   * @description: 删除cookie
   * @param {string} key
   * @param {object} options
   * @return {void}
   */
  removeItem(key, options = {}) {
    this.setItem(key, '', -1, options);
  }
  /**
   * @description: 计算属性，获取cookie长度
   * @return {Number}
   */
  get length() {
    return (document.cookie.match(/[^ =;]+(?==)/g) || []).length;
  }
  /**
   * @description: 清空所有cookie
   * @param {object} options
   * @return {void}
   */
  clear(options = {}) {
    (document.cookie.match(/[^ =;]+(?==)/g) || []).forEach(key => {
      this.removeItem(decodeURIComponent(key), options);
    });
  }
}

const cookieStorage = new CookieStorage();

export default cookieStorage;